pp108 : Validating a Page Using jQuery Validation Plug-in

Validating a Page Using jQuery Validation Plug-in

This topic describes the procedure to validate a page using the jQuery validation plug-in.

This example describes the procedure to make a field mandatory such as input box or select box, and specify the validation rule such as minimum or maximum range. It is built on the Employees table from the Northwind Database and displays the employees form with the field validations. If all the mandatory fields are provided and the specified rules are met for the field, the employee data is saved in the Employees table.

The following steps are involved in this example:

  1. Including jQuery validation plug-in
  2. Adding the required attribute
  3. Adding other validation attributes
  4. Adding the validate method
  5. Invoking the Validate method

Including jQuery validation plug-in

The jQuery validation plug-in is used to validate fields and consists of many validation customization options. Refer to the jQuery website for more information. To include the jQuery validation plug-in, you must add the script jquery.validate.js in your Web page using the following code block:

<script
    src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js" type="text/javascript"/>

Adding the required attribute

You must add the required attribute to make a field mandatory as follows:

Required Elements
<input type="text" name="fldFirstName" data-bind="value:FirstName" id="fldFirstName" required />

Adding other validation attributes

You can also add other validation attributes for a field as follows:

Attribute Description Example
required Makes the element mandatory
<input id="field" name="field" required />
minlength Minimum length allowed for the element
<input id="field" name="field" minlength="3" />
maxlength Maximum length allowed for the element
<input id="field" name="field" maxlength="15" />
min Minimum value required for the element
<input id="field" name="field" min="13" />
max Maximum value allowed for the element
<input id="field" name="field" max="23" />
email Validates the email address
<input id="field" name="field" email="true" />
url Validates the URL
<input id="field" name="field" url="true" />
date Validates the date
<input id="field" name="field" date="true" />
dateISO Validates if the provided date is an ISO date
<input id="field" name="field" dateISO="true" />
number Validates if the provided number is a decimal number
<input id="field" name="field" number="true" />
digits Validates if the input consists of digits only
<input id="field" name="field" digits="true" />
creditcard Validates the credit card number
<input id="field" name="field" creditcard="true" />
equalTo Validates if two inputs have the same value by comparing them
<input id="password" name="password" />
<input id="password_again" name="password_again" equalTo="#password"/>

In this example, the minlength and maxlength attributes are specified for the First Name field as follows:

Required Elements
<input type="text" name="fldFirstName" data-bind="value:FirstName" id="fldFirstName" required minlength="3" maxlength="15"/>

Adding the validate method

You can add the validate method to validate the fields based on the specified attributes. In the following code block, employeeForm is the ID of the form:

Validate Method
$("#employeeForm").validate();

Some options provided by the validate method are as follows:

  • Rules: These are the key or value pairs for defining custom rules. Key is the name of an element or a group of check boxes or radio buttons. Value is an object consisting of the rule, parameter pairs, or a plain string. The following example specifies name and email elements as required using the shortcut for a single rule; a valid email address using another object literal:
    Example
    $(".selector").validate({
      rules: {
        // simple rule, converted to {required:true}
        name: "required",
        // compound rule
        email: {
          required: true,
          email: true
        }
      }
    });
  • Error Placement: You can define the placement of the created error labels. The following example uses a table layout for the form, placing error messages in the next cell after the input:
    Example
    $("#myform").validate({
      errorPlacement: function(error, element) {
        error.appendTo( element.parent("td").next("td") );
      }
    });

    The callback function consists of error and element parameters. The error is the error label to be inserted in the DOM and element is the validated input for relative positioning.

Refer to the jQuery website for more information on the options available for the validate method.

Invoking the validate method

You can invoke the validate method using the valid method. This method returns the Boolean value true if all the conditions are satisfied; else, it returns false.

Valid Method
$("#employeeForm").valid();

In this example, the valid method is invoked on the Save action. If all the mandatory fields are provided and the specified rule is met for the first name, the employee details are saved in the Employees table. The following code block displays the Employee Details:

Employee Details
<!DOCTYPE html>
<html>
    <head>
    <title>Employees</title>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <link rel="stylesheet" href="/cordys/thirdparty/jquery/cordys.min.css" type="text/css" />
    <link rel="stylesheet" href="/cordys/thirdparty/jquery/jquery.mobile.structure.min.css" type="text/css" />
    <style type="text/css">    
    label.error {
        color: red;
        margin-top: 0.5em;
        width: 100%;
        float: right;
    }
    </style>
    <script src="/cordys/thirdparty/jquery/jquery.js" type="text/javascript"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js" type="text/javascript"></script>
    <script src="/cordys/thirdparty/jquery/jquery.mobile.min.js" type="text/javascript"></script>

    <script src="/cordys/thirdparty/knockout/knockout.js" type="text/javascript"></script>
    <script src="/cordys/html5/cordys.html5sdk.js" type="text/javascript"></script>

    <script type="text/javascript">
        var empModel; // Reference to the model
        // Create a new model on page ready
        $(function() {
            empModel = new $.cordys.model({
                context: document.body,
                objectName: "Employees", // Name of the Business Object
                isReadOnly: false,
                // Common settings for all methods - read, create, update, delete, synchronize
                defaults: {
                    namespace: "http://schemas.cordys.com/NW",
                    dataType: "json"
                }
            });
            
            //Set the newly added Business Obect as the currently selected item
            var newEmployee = empModel.addBusinessObject({Address: "",Country: "",FirstName: "",LastName: "",Notes: "",TitleOfCourtesy: ""});
            empModel.selectedItem(newEmployee);

            // Validate method for validating the form fields
			$("#employeeForm").validate();

            $("#btnSave").on("click", function() {
                // valid() will call the validate() method for validating the required fields and specified rules
                if($("#employeeForm").valid()){
                    empModel.create({method:"Update"}).done(function() {
                        showMessage("Employee details have been saved.");
                    })
                }
            })
        });
    </script>
</head>

<body>
    <div data-role="page" id="mainPage">
        <div data-role="header" data-theme="b">
            <h1>Employees</h1>
        </div>
        <div data-role="content" data-theme="c">
            <form id="employeeForm" method="get">
                <fieldset data-bind="with: selectedItem">
                    <div>
                        <label for="fldFirstName" class="ui-input-text">First Name*</label>
                        <input type="text" name="fldFirstName" data-bind="value:FirstName" id="fldFirstName" required minlength="3" maxlength="15" />
                    </div>
                    <div>
                        <label for="fldLastName" class="ui-input-text">Last Name*</label>
                        <input type="text" name="fldLastName"  data-bind="value:LastName"  id="fldLastName" required/>
                    </div>
                    <div >
                        <label for="fldAddress" class="ui-input-text">Address*</label>
                        <input type="text" name="fldAddress" data-bind="value:Address" id="fldAddress" required/>
                    </div>
                    <div >
                        <label for="fldCountry" class="ui-input-text">Country*</label>
                        <input type="text" name="fldCountry" data-bind="value:Country" id="fldCountry" required/>
                    </div>
                    <div >
                        <label for="fldNotes" class="ui-input-text">Notes</label>
                        <textarea id="fldNotes" data-bind="value:Notes"></textarea>
                    </div>
                    <div data-role="controlgroup">
                        <input id="btnSave"  data-theme="b" type="button" value="Save" />
                    </div>
                </fieldset>
            </form>
        </div>
    </div>
</body>
</html>

Refer to jQuery Demos for more demos.